<template>
  <div>
    <div class="query-form">
    <el-form
      :model="queryForm"
      ref="queryFormRef"
      label-width="100px"
      :inline="true"
    >

      <el-form-item label="供应商名称">
        <!-- <el-input v-model="queryForm.vender" placeholder="请输入供应商名称或供应商编码" style="width: 200px" /> -->
        <el-input
            v-model="queryForm.vender"
            placeholder="双击选择供应商"
            @dblclick="openSupplierDialog"
            readonly>
          </el-input>
      </el-form-item>

      <el-form-item label="商品信息">
        <el-input v-model="queryForm.goodsDesc" placeholder="请输入商品名称或商品编码" style="width: 260px" />
      </el-form-item>
      <el-form-item label="创建人">
        <el-input v-model="queryForm.creater" placeholder="请输入创建人" style="width: 200px" />
      </el-form-item>

      <el-form-item label="创建日期">
        <el-date-picker
          v-model="currentDate"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          style="width: 300px"
        />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="load">查询</el-button>
      </el-form-item>
    </el-form>
     <div>
    <!-- 上传按钮 -->
    <el-button type="success" style="margin: 10px;" @click="showUploadDialog = true">
      上传
    </el-button>

    <!-- 上传弹窗 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传"
      width="500px"
      :close-on-click-modal="false"
    >
    <el-form-item label="上传图片">
      <!-- 上传区域 -->
      <el-upload
        class="upload-demo"
        :http-request="customUpload"
        list-type="picture-card"
        :on-success="handleUploadSuccess"
        :show-file-list="true"
        name="file"
        :headers="{ token: dataInfo.user.accessToken }"
        :on-remove="handleRemove"
            >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-form-item>


      <!-- 备注输入 -->
      <el-form :model="uploadForm" label-width="60px">
        <el-form-item label="备注">
          <el-input
            v-model="uploadForm.remark"
            placeholder="请输入备注"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="success" @click="handleSubmit">确定上传</el-button>
      </template>
    </el-dialog>
  </div>
  </div>
      <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hnyyPurRebateList.hnyyPurRebateListId" label="序号" width="100" />
        <el-table-column
          prop="hnyyPurRebateList.createDate"
          label="创建时间"
          width="180"
          :formatter="formatDate2"
        />
        <el-table-column prop="hnyyPurRebateList.creater" label="创建人" width="100" />
        <el-table-column prop="venderCode" label="供应商代码" width="100" />
        <el-table-column prop="venderName" label="供应商名称" width="180" />
        <el-table-column prop="planer" label="采购员" width="80" />
        <el-table-column prop="comGoodsId" label="商品ID" width="80" />
        <el-table-column prop="goodsOpcode" label="商品代码" width="100" />
        <el-table-column prop="goodsName" label="商品名称" width="220" />
        <el-table-column prop="goodsDesc" label="商品规格" width="120" />
        <el-table-column prop="packageNum" label="包装数量" width="90" />
        <el-table-column prop="unitName" label="单位" width="60" />
        <el-table-column prop="defaultPrice" label="进价" width="80" />
        <el-table-column prop="purTaxRate" label="品种税率" width="100" />
        <el-table-column prop="lastPurInvoicePrice" label="上次发票价格" width="110" />
        <el-table-column
          prop="lastPurInvoiceDate"
          label="首营日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column label="政策维护" width="90">
          <template #default="scope">
            <el-icon
              style="cursor: pointer; color: #409EFF; font-size: 25px;"
              @click="openPolicyDialog(scope.row)"
            >
              <Edit />
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column prop="productLocation" label="上市许可持有人/生产厂家" width="200" />
        <el-table-column
          prop="createDate"
          label="首营日期"
          width="100"
          :formatter="formatDate"
        />

        <el-table-column prop="peyMethod" label="付款策略" width="100" />
        <el-table-column prop="peyDays" label="付款天数" width="90" />
        <el-table-column prop="abcType" label="ABC分类" width="90" />
        <el-table-column prop="marketCode" label="交易编码" width="120" />
      </el-table>
       <!-- 政策维护弹窗 -->
     <el-dialog v-model="policyDialogVisible" title="价格联系政策维护" width="1000" :before-close="handleClose">
    <el-form
      :model="policyForm"
      label-width="100px"
      :inline="true"
    >
      <el-form-item label="生产厂家" prop="vender.productLocation">
        <el-input v-model="policyForm.vender.productLocation" disabled style="width: 240px"/>
      </el-form-item>

      <el-form-item label="商品ID" prop="comGoodsId">
        <el-input v-model="policyForm.comGoodsId" disabled style="width: 80px" />
      </el-form-item>

      <el-form-item label="商家信息" prop="vender.goodsInfo">
        <el-input v-model="policyForm.vender.goodsInfo" disabled style="width: 450px" />
      </el-form-item>

      <el-form-item label="供应商代码" prop="vender.venderCode">
        <el-input v-model="policyForm.vender.venderCode" disabled style="width: 100px" />
      </el-form-item>

      <el-form-item label="供应商名称" prop="vender.venderName">
        <el-input v-model="policyForm.vender.venderName" disabled style="width: 240px"/>
      </el-form-item>

      <el-form-item label="政策类型" prop="hnyyPurType">
        <el-select v-model="policyForm.hnyyPurType" placeholder="请选择政策类型" style="width: 150px" disabled>
          <el-option label="采购折让" value="1" />
          <el-option label="销售折让" value="2" />
          <el-option label="二次扣点" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="取值来源" prop="hnyyPurRebateFromType">
        <el-select v-model="policyForm.hnyyPurRebateFromType" placeholder="请选择取值来源" style="width: 150px" disabled>
          <el-option label="销售流向" value="1" />
          <el-option label="购进流向" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="协议起始期" prop="startDate">
        <el-date-picker v-model="policyForm.startDate" placeholder="请选择开始日期" type="date" style="width: 200px" disabled/>
      </el-form-item>

      <el-form-item label="协议结束期" prop="endDate">
        <el-date-picker v-model="policyForm.endDate" placeholder="请选择结束日期" type="date" style="width: 200px" disabled/>
      </el-form-item>

      <el-form-item label="折让计算期间" prop="hnyyRebateModueId" label-width="120px">
        <el-select v-model="policyForm.hnyyRebateModueId" placeholder="请选择折让计算期间" style="width: 140px" disabled>
          <el-option label="月度" value="1" />
          <el-option label="季度" value="2" />
          <el-option label="半年度" value="3" />
          <el-option label="年度" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="折让方式" prop="hnyyRebateMethdId">
        <el-select v-model="policyForm.hnyyRebateMethdId" placeholder="请选择折让方式" style="width: 160px" disabled>
          <el-option label="票扣" value="1" />
          <el-option label="红票" value="2" />
          <el-option label="现金" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="采购折让类型" prop="hnyyRebateTypeId" label-width="120px">
        <el-select v-model="policyForm.hnyyRebateTypeId" placeholder="请选择采购折让类型" style="width: 160px" disabled>
          <el-option label="付款折让" value="1" />
          <el-option label="已销定返" value="2" />
          <el-option label="总量折让" value="3" />
          <el-option label="税率补偿" value="4" />
          <el-option label="扫码补偿" value="5" />
          <el-option label="二次销售" value="6" />
        </el-select>
      </el-form-item>

      <el-form-item label="中标价" prop="zbPrice">
        <el-input v-model="policyForm.zbPrice" style="width: 100px" disabled/>
      </el-form-item>

      <el-form-item label="进价" prop="purPrice">
        <el-input v-model="policyForm.purPrice" style="width: 100px" disabled/>
      </el-form-item>

      <el-form-item label="品种税率" prop="goodsRate">
        <el-select v-model="policyForm.goodsRate" placeholder="请选择品种税率" style="width: 150px" disabled>
          <el-option label="0.00" value="0.00" />
          <el-option label="0.01" value="0.01" />
          <el-option label="0.03" value="0.03" />
          <el-option label="0.06" value="0.06" />
          <el-option label="0.09" value="0.09" />
          <el-option label="0.13" value="0.13" />
          <el-option label="0.16" value="0.16" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户代码" prop="clientId">
        <el-input
          v-model="policyForm.clientId"
          placeholder="双击选择客户"
          disabled
          readonly
          style="width:200px"
        />
      </el-form-item>

      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="policyForm.clientName" placeholder="客户名称" disabled style="width: 200px"/>
      </el-form-item>

      <el-form-item label="客户集合" prop="sysClientPriceSetsList">
        <el-input
          v-model="policyForm.sysClientPriceSetsList"
          placeholder="双击选择客户集合"
          style="width: 460px"
          disabled
        />
      </el-form-item>

      <el-form-item label="采购折让比率" prop="purRate">
        <el-input
          v-model="policyForm.purRate"
          placeholder="保留两位小数"
          style="width: 120px"
          disabled
        />
      </el-form-item>

      <el-form-item label="采购折让单价" prop="purRebatePrice">
        <el-input
          v-model="policyForm.purRebatePrice"
          placeholder="请输入"
          style="width: 120px"
          disabled
        />
      </el-form-item>

      <el-form-item label="付款账期（天数）" label-width="180px" prop="payDay">
        <el-input v-model="policyForm.payDay" placeholder="请输入整数" style="width: 120px" disabled/>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 弹窗查询供应商 -->
    <el-dialog title="选择供应商" v-model="supplierDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="supplierQuery"
            placeholder="请输入供应商名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="searchSupplier">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="supplierList"
        style="width: 100%;"
        @row-click="selectSupplier">
        <el-table-column prop="comPartyId" label="供应商ID" width="120" />
        <el-table-column prop="partyOpcode" label="供应商代码" />
        <el-table-column prop="partyName" label="供应商名称" />
      </el-table>
       <!-- 分页 -->
    <div style="margin-top: 10px; text-align: right;">
      <el-pagination
        v-model:current-page="dataVender.pageNum"
        v-model:page-size="dataVender.pageSize"
        :total="dataVender.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="searchSupplier"
        @current-change="searchSupplier"
      />
  </div>
    </el-dialog>
  </div>
  <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next"
          :total="data.total"
          :page-sizes="[20, 40, 80]"
          @current-change="load"
          @size-change="load"
      />
    </div>
</template>

<script setup>
import { ref,reactive,nextTick  } from 'vue';
import request from '@/utils/request';
import { Edit } from '@element-plus/icons-vue'
import dayjs from "dayjs";
import { ElLoading } from 'element-plus';
import {ElMessage } from 'element-plus'
import {currentDate} from '../../utils/time.js';
import { Plus } from '@element-plus/icons-vue'

let loadingInstance = null;
// 供应商查询分页查询参数
const dataVender = ref({
  pageNum: 1,
  pageSize: 20,
  total:0
})
// 查询到的供应商列表
const supplierList = ref([])
// 弹窗查询关键字
const supplierQuery = ref('')
const imageList = ref([])
const imageUrl = ref('')
const dataInfo =reactive({
    user: JSON.parse(localStorage.getItem("code_user")||"{}"),
})

const showUploadDialog = ref(false)
const uploadForm = ref({
  remark: ''
})
// 弹窗显示状态
const supplierDialogVisible = ref(false)
// 打开供应商弹窗
const openSupplierDialog = () => {
  supplierDialogVisible.value = true
}
// 查询供应商
const searchSupplier = () => {
  if(!supplierQuery.value)
  return ElMessage.warning('请输入供应商名称')
 nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body', // 👈 重点，挂载在 el-dialog 内容区
      text: '加载中...'
    });
  });
  request.get('/link/getParty', {params: { name: supplierQuery.value ,pageNum:dataVender.value.pageNum,pageSize:dataVender.value.pageSize} }).then((res)=>{
    console.log('res=======> ',res)
    if(res.code === 200){
      supplierList.value = res.data.list
      dataVender.value.total = res.data.total
    }
  })
  .catch((err) => {
    console.error('请求失败', err);
  }).finally(() => {
    if (loadingInstance) loadingInstance.close();
  });
}
// 点击供应商列表选择
const selectSupplier = (row) => {
  queryForm.venderId = row.comPartyId
  queryForm.vender = row.partyName
  supplierDialogVisible.value = false
}

// 上传文件处理
const customUpload = async (option) => {
  const formData = new FormData()
  formData.append('file', option.file)
  formData.append('remark', uploadForm.value.remark)

  try {
    const res = await request.post('/api/uploadPolicy', formData)
    option.onSuccess(res)
    ElMessage.success('上传成功')
  } catch (err) {
    console.error('上传失败:', err)
    option.onError(err)
    ElMessage.error('上传失败')
  }
}

const handleUploadSuccess = (response) => {
  if (response?.url) {
    imageList.value.push(response.url)
    imageUrl.value = imageList.value.join(',')
  }
}

const handleRemove = (file) => {
  console.log('file====>',file)
  const url = file.response?.url || file.url
  if (url) {
    imageList.value = imageList.value.filter(item => item !== url)
    imageUrl.value = imageList.value.join(',')
  }
}

const selectedRows = ref([]) // 存储选中的数据

const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 查询条件
const queryForm=reactive({
  vender:'',
  venderId:'',
  goodsDesc:'', // 商品信息
  creater:'', // 创建人
})
// 政策维护弹窗
const policyDialogVisible = ref(false);
// 政策维护数据
const data=ref({
  pageNum:1,
  pageSize:20,
  total:0
})
const policyForm=reactive({})

const formatDate2=(row, column, cellValue)=>{
   if (!cellValue) return '';
    // 转换成 Date 对象
    const date = new Date(cellValue);
    // 格式化
    return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} `
         + `${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}:${String(date.getSeconds()).padStart(2,'0')}`;
}
// 时间格式化
const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}
const tableData = ref([]);
const openPolicyDialog=(row)=>{
  console.log('row',row)
  // 打开政策维护弹窗
  policyDialogVisible.value = true;
  Object.assign(policyForm, row.hnyyPurRebateList)
  if(policyForm.clientName===undefined && policyForm.clientId){
    request.get('/link/getClientById',{params:{clientId:policyForm.clientId}}).then((res) => {
      console.log('res====>',res)
      if (res.code === 200) {
        policyForm.clientName=res.data[0].partyName
      }
    })
  }
  if(policyForm.sysClientPriceSetsList){
    sysClientPriceSetsListId.value=policyForm.sysClientPriceSetsList
    request.get('/link/getSysClientPriceSets',{params:{sysClientPriceSetsList:policyForm.sysClientPriceSetsList}}).then((res) => {
      console.log('res====>121',res)
      if (res.code === 200) {
        policyForm.sysClientPriceSetsList = res.data
      }
    })
  }
  policyForm.vender.productLocation=row.productLocation
  policyForm.vender.venderName=row.venderName
  policyForm.vender.goodsInfo=row.goodsOpcode+' / ' +row.goodsName+' / ' +row.goodsDesc+' / ' +row.unitName
  policyForm.vender.venderCode=row.venderCode
  policyForm.zbPrice=row.defaultPrice
  policyForm.purPrice=row.defaultPrice
  policyForm.venderId=row.venderPartyId
  policyForm.comGoodsId=row.comGoodsId
}
const load=()=>{
  if (queryForm.vender==='') {
    ElMessage.warning('请先选择供应商进行查询')
    return false // 阻止上传
  }
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '数据加载中，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)',
  });
  console.log('queryForm.endDate',currentDate.value[0],)
  // 格式化日期为 yyyy-MM-dd
  const startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  const endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  request.get('/link/getCheck',{
    params:{
      pageNum: data.value.pageNum,
      pageSize: data.value.pageSize,
      key: 2,
      vender: queryForm.vender,
      goodsDesc: queryForm.goodsDesc,
      creater: queryForm.creater,
      startDate:startDate,
      endDate:endDate
    }
  }).then((res) => {
    console.log('res',res)
    if (res.code === 200) {
      tableData.value = res.data.list
      data.value.pageNum = res.data.pageNum
      data.value.total = res.data.total;
    } else {
      console.error('Error loading data:', res.message);
    }
  }) .catch((err) => {
      console.error('请求失败', err);
      ElMessage.error('加载失败，请稍后再试');
    })
    .finally(() => {
      loadingInstance.close();
    });
}
// load();

// 提交上传
const handleSubmit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先勾选需要上传的数据')
    return false // 阻止上传
  }
  console.log('selectedRows',selectedRows.value)
  request.get('/protocol/addPolicy', {
    params:{
      venderNo: queryForm.venderId,
      memo:uploadForm.value.remark
    }
  }).then((res) => {
    if (res.code === 200 && res.data !== '') {
      request.post('/protocol/addVenderList',{
          venderId:res.data,
          listId:selectedRows.value.map(item=>item.hnyyPurRebateList.hnyyPurRebateListId)
      }).then((res2)=>{
        if(res2.code===200){
          request.get('/protocol/addVenderFile',{
            params:{
              venderId:res.data,
              fileName:imageUrl.value
            }
          }).then((res3)=>{
            if(res3.code===200){
              policyDialogVisible.value = false
              ElMessage.success('上传成功')
              uploadForm.value.remark=''
              imageList.value=[]
              load()

            }else{
              ElMessage.error(res3.msg || '上传失败3')
            }
          })
          ElMessage.success('上传成功')
        }else{
          ElMessage.error(res2.msg || '上传失败2')
        }
      })

      showUploadDialog.value = false
    } else {
      ElMessage.error('上传失败')
    }
  })
}
</script>

<style>

</style>
